<template>
  <div class="load">
    <!-- <div class="loading" v-show="isLoading"></div> -->
  </div>
</template>

<script>
  import _ from 'lodash'

  export default {
    name: 'load',
    props: {
      loadEvent: {
        type: Function,
        // default: function() {
        //   return new Promise(resolve => {
        //     resolve();
        //   })
        // }
      }
    },
    data() {
      return {
        scrollH: 0,
        isLoading: false
      }
    },
    mounted() {
      window.addEventListener('scroll', this.handleScroll)
      // console.log("jia zai")
      // this.loadEvent()
    },
    methods: {
      handleScroll() {
        // return
        // 向下滚动时加载
        let that = this;
        let direction;
        direction = this.getScrollBottomHeight() - this.scrollH;
        this.scrollH = this.getScrollBottomHeight();

        if(this.getScrollBottomHeight() <= 30 && direction < 0) {
          if (this.isLoading == true) {
            return
          }
          this.isLoading = true;
          // this._loadEvent()
          let result = this.loadEvent()
          result.then(() => {
            that.isLoading = false;
          })
        }
      },
      // _loadEvent: _.throttle(function(){
      //   this.loadEvent()
      //   this.isLoading = false;
      // },1000),
      //滚动条顶到底部的距离
      getScrollBottomHeight() {
          return this.getPageHeight() - this.getScrollTop() - this.getWindowHeight();
      },
      //页面高度
      getPageHeight() {
          return document.querySelector("html").scrollHeight
      },
      //滚动条顶 高度
      getScrollTop() {
          var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
          if (document.body) {
              bodyScrollTop = document.body.scrollTop;
          }
          if (document.documentElement) {
              documentScrollTop = document.documentElement.scrollTop;
          }
          scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
          return scrollTop;
      },
      getWindowHeight() {
          var windowHeight = 0;
          if (document.compatMode == "CSS1Compat") {
              windowHeight = document.documentElement.clientHeight;
          } else {
              windowHeight = document.body.clientHeight;
          }
          return windowHeight;
      }
    }
  }
</script>

<style lang="less">
  @import '~COMMON/common.less';

  .load {
    .loading {
      margin: 0 auto;
      width: 20px;
      height: 20px;
      background: url(~IMGS/loading.gif) no-repeat;
      background-size: 100%;
    }
  }
</style>